<script setup>
import { ref } from 'vue'
import { useAuthStore } from '@/stores/modules/auth'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
// 导入图标库
import {User, Lock } from '@element-plus/icons-vue'
const loginForm = ref({
  username: '',
  password: ''
})
const formRef = ref()
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 15, message: '用户名必须是5-15位的字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符',
      trigger: 'blur'
    }
  ]

}
const authStore = useAuthStore()
const router = useRouter()

const login = async () => {
  try {
    await formRef.value.validate()
    await authStore.handleLogin(loginForm.value)
    ElMessage.success('登录成功！')
    router.push('/')
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '用户名或密码错误')
  }
}

</script>

<template>
  <div class="login-page">
    <el-card class="login-card">
      <template #header>
        <h2>用户登录</h2>
      </template>

      <el-form
      ref="formRef"
      :model="loginForm"
      :rules="rules"
      @submit.prevent="login"
      label-position="top"
      >
        <el-form-item label="用户名" required prop="username">
          <el-input :prefix-icon="User" v-model="loginForm.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="密码" required prop="password">
          <el-input
            :prefix-icon="Lock"
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="login" style="width: 100%">
            登录
          </el-button>
        </el-form-item>
      </el-form>

      <div class="link-text">
        还没有账号？ <el-link type="primary"  @click="router.push('/register')">立即注册</el-link>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.login-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.login-card {
  width: 400px;
  max-width: 90%;
}

.login-card h2 {
  text-align: center;
  margin: 0;
  color: #303133;
}

.link-text {
  text-align: center;
  margin-top: 20px;
  color: #606266;
}
</style>
